﻿using RQX.Common.Web.Config;
using RQX.Common.Web.Tools;
using System;
using System.IO;
using System.Text;

namespace RQX.Common.Web.Logger
{
    public class LoggerHelper
    {
        private static readonly string DefaultPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");
        private const string LogFormat = "{0}\t{1}";
        private static readonly string DirPath;

        static LoggerHelper()
        {
            var path = AppConfigurtaion.GetConfigValue($"{GlobalConfig.LoggerPath}");
            DirPath = path.IsNullOrEmpty() ? DefaultPath : path;
        }

        #region 本地日志
        /// <summary>
        /// 写文本日志
        /// </summary>
        /// <param name="msg"></param>
        public static void WriteLocalLog(string msg)
        {
            WriteLocal(msg);
        }

        private static string GetLocalLine(string msg)
        {
            return string.Format(LogFormat, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), msg);
        }


        private static void WriteLocal(string msg)
        {
            if (!Directory.Exists(DirPath))
            {
                Directory.CreateDirectory(DirPath);
            }
            var filePath = Path.Combine(DirPath, DateTime.Now.ToString("yyyy-MM-dd") + ".log");
            try
            {
                using var sw = new StreamWriter(filePath, true, Encoding.UTF8);
                sw.WriteLine(GetLocalLine(msg));
            }
            catch { }
        }

        #endregion
    }
}
